package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.constant.BompAppParamConstant;
import cc.rengu.igas.bomp.common.constant.BompTreeNodeConstant;
import cc.rengu.igas.bomp.common.dao.BompMcInfoMapper;
import cc.rengu.igas.bomp.common.dao.BompTCRoleAcctInfoMapper;
import cc.rengu.igas.bomp.common.dao.BompTMMcFundInfoMapper;
import cc.rengu.igas.bomp.common.dao.MchntBaseInfoMapper;
import cc.rengu.igas.bomp.common.dao.impl.BompMcInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.BompTCRoleAcctInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.BompTMMcFundInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntBaseInfoMapperImpl;
import cc.rengu.igas.bomp.common.entity.BompMcInfo;
import cc.rengu.igas.bomp.common.entity.BompTCRoleAcctInfo;
import cc.rengu.igas.bomp.common.entity.BompTMMcFundInfo;
import cc.rengu.igas.bomp.common.entity.MchntBaseInfo;
import cc.rengu.igas.bomp.common.enums.AcctStatusEnum;
import cc.rengu.igas.bomp.common.enums.BompTMMcFundInfoFundStatusEnum;
import cc.rengu.igas.bomp.common.enums.PayerAcctTypeEnum;
import cc.rengu.igas.bomp.common.enums.RespCodeEnum;
import cc.rengu.igas.bomp.core.model.UserSessionInfo;
import cc.rengu.igas.bomp.core.realize.UserPermissionCheckService;
import cc.rengu.igas.bomp.core.realize.impl.UserPermissionCheckServiceImpl;
import cc.rengu.igas.bomp.core.service.base.PayService;
import cc.rengu.igas.bomp.facade.base.Header;
import cc.rengu.igas.bomp.facade.request.MompPaymentRequest;
import cc.rengu.igas.bomp.facade.response.MompPaymentResponse;
import cc.rengu.igas.momp.facade.request.MchntMcPublishRequest;
import cc.rengu.igas.share.common.util.GlobalEsbUtil;
import cc.rengu.jradp.mods.dbs.Database;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.dao.MchntOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.PayOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.SysParamMapper;
import cc.rengu.oltp.service.common.dao.UserOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.MchntOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.PayOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.SysParamMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.UserOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.*;
import cc.rengu.oltp.service.common.enums.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.BinInfoService;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.OrderService;
import cc.rengu.oltp.service.realize.SmsService;
import cc.rengu.oltp.service.realize.impl.BinInfoServiceImpl;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.service.realize.impl.SmsServiceImpl;
import cc.rengu.oltp.utility.util.*;
import cc.rengu.utility.reflect.JsonUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author Xuegui Cao
 * @date 2020/7/17
 * @description 营销打款
 */
public class MompPaymentService extends PayService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        MompPaymentRequest mompPaymentRequest = new MompPaymentRequest();
        ConvertUtil.convertOutput(mompPaymentRequest);
        return mompPaymentRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        BizResponse bizResponse = new BizResponse();
        MompPaymentRequest mompPaymentRequest = (MompPaymentRequest) request;
        MompPaymentResponse mompPaymentResponse = new MompPaymentResponse();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setResult(mompPaymentResponse);
        Header requestHeader = mompPaymentRequest.getHeader();
        mompPaymentResponse.setHeader(requestHeader);
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        rglog.info("业务处理开始,系统流水号:<{}>", sysSeqNum);
        String instId = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID);
        String chanlId = mompPaymentRequest.getHeader().getChanlId();
        String mcNo = mompPaymentRequest.getMcNo();
        String payerAcctId = "";
        String payerAcctType = "";

        /*业务前校验*/
        mompPaymentRequest = beforeBizCheck(mompPaymentRequest);

        String esbSysSeqNum = GlobalEsbUtil.generateEsbSeqeuenceNumber(instId);//ESB流水号
        xmlTreeUtil.setXmlTreeStringValue(BompTreeNodeConstant.ESB_SYS_SEQ_NUM, esbSysSeqNum);
        mompPaymentResponse.setAcctSeqNum(esbSysSeqNum);

        if (BompAppParamConstant.MCMP_CHANNEL.equals(mompPaymentRequest.getHeader().getChanlId())) {
            payerAcctId = instId;
            payerAcctType = PayerAcctTypeEnum.BANK.getCode();
        } else if ("WECHAT".equals(chanlId) || "MOBILE".equals(chanlId) || "PCWEB".equals(chanlId)) {
            //BSPS调用
            payerAcctId = mompPaymentRequest.getMchntNo();
            payerAcctType = PayerAcctTypeEnum.MCHNT.getCode();
        }

        BompTMMcFundInfoMapper tmMcFundInfoMapper = new BompTMMcFundInfoMapperImpl();
        List<BompTMMcFundInfo> bompTMMcFundInfoList = tmMcFundInfoMapper.selectBompTMMcFundInfoByInstIdAndMcNoAndDescByCreateTime(instId, mcNo, payerAcctId, payerAcctType);
        if (bompTMMcFundInfoList == null || bompTMMcFundInfoList.size() == 0) {
            //正常打款
            rglog.info("没有打款记录,正常打款.");
            return normalPayment(mompPaymentRequest, mompPaymentResponse, bizResponse);
        } else {
            //存在打款记录,判断最新打款记录的打款状态
            BompTMMcFundInfo lastBompTMMcFundInfo = bompTMMcFundInfoList.get(0);
            xmlTreeUtil.setXmlTreeObjectValue("bompTMMcFundInfo", lastBompTMMcFundInfo);
            rglog.debug("最新打款记录:<{}>", JsonUtil.toJson(lastBompTMMcFundInfo));
            if (BompTMMcFundInfoFundStatusEnum.SUCCESS.getStatus().equals(lastBompTMMcFundInfo.getFundStatus())) {
                //已成功打款
                rglog.info("已有成功打款记录,拒绝打款.");
                /*商户服务平台调用时,成功后调用营销发布*/
                if ("WECHAT".equals(chanlId) || "MOBILE".equals(chanlId) || "PCWEB".equals(chanlId)) {
                    mchntMcPublish(mcNo);
                }
                mompPaymentResponse.setAcctStatus(AcctStatusEnum.SUCCESS.getAcctStatus());
                mompPaymentResponse.setFailureReason(RespCodeEnum.PAY_IS_DONE.getRespDesc());
                mompPaymentResponse.setRespCode(RespCodeEnum.PAY_IS_DONE.getRespCode());
                mompPaymentResponse.setRespDesc(RespCodeEnum.PAY_IS_DONE.getRespDesc());
                bizResponse.setRespCode(mompPaymentResponse.getRespCode());
                bizResponse.setRespDesc(mompPaymentResponse.getRespDesc());
                return bizResponse;
            } else if (BompTMMcFundInfoFundStatusEnum.TIMEOUT.getStatus().equals(lastBompTMMcFundInfo.getFundStatus())) {
                //上次打款超时,调用同步查证
                rglog.info("上次打款超时,开始调用【通用查证】服务.");
                int queryResult = queryOrderDone(mompPaymentRequest);
                if (1 == queryResult) {
                    rglog.info("原交易成功,更新订单状态、营销打款打款状态为【成功】");

                    boolean bUpdateOrderResult = isUpdateOrigOrderStauts(mompPaymentRequest, TransStatusEnum.TRANS_SUCC.getStatus());
                    rglog.info("更新订单表结果:<{}>", bUpdateOrderResult);

                    boolean bUpdateTMMcResult = isUpdateTMMcFundInfo(lastBompTMMcFundInfo, mompPaymentRequest.getUserId(), BompTMMcFundInfoFundStatusEnum.SUCCESS.getStatus());
                    rglog.info("更新打款记录表结果:<{}>", bUpdateTMMcResult);

                    /*商户服务平台调用时,成功后调用营销发布*/
                    if ("WECHAT".equals(chanlId) || "MOBILE".equals(chanlId) || "PCWEB".equals(chanlId)) {
                        mchntMcPublish(mcNo);
                    }

                    mompPaymentResponse.setAcctStatus(AcctStatusEnum.SUCCESS.getAcctStatus());
                    mompPaymentResponse.setFailureReason(RespCodeEnum.PAY_IS_DONE.getRespDesc());
                    mompPaymentResponse.setRespCode(RespCodeEnum.PAY_IS_DONE.getRespCode());
                    mompPaymentResponse.setRespDesc(RespCodeEnum.PAY_IS_DONE.getRespDesc());
                    bizResponse.setRespCode(mompPaymentResponse.getRespCode());
                    bizResponse.setRespDesc(mompPaymentResponse.getRespDesc());
                    return bizResponse;
                } else if (2 == queryResult) {
                    rglog.info("原交易失败,更改订单状态、营销打款打款状态为为【失败】");

                    boolean bUpdateOrderResult = isUpdateOrigOrderStauts(mompPaymentRequest, TransStatusEnum.SYSTEM_REJECT.getStatus());
                    rglog.info("更新订单表结果:<{}>", bUpdateOrderResult);

                    boolean bUpdateTMMcResult = isUpdateTMMcFundInfo(lastBompTMMcFundInfo, mompPaymentRequest.getUserId(), BompTMMcFundInfoFundStatusEnum.FAILURE.getStatus());
                    rglog.info("更新打款记录表结果:<{}>", bUpdateTMMcResult);

                    mompPaymentResponse.setAcctStatus(AcctStatusEnum.FAIL.getAcctStatus());
                    mompPaymentResponse.setFailureReason("上次打款失败,请重新打款.");
                    mompPaymentResponse.setRespCode(RespCodeEnum.SYSTEM_ERROR.getRespCode());
                    mompPaymentResponse.setRespDesc(RespCodeEnum.SYSTEM_ERROR.getRespDesc());
                    bizResponse.setRespCode(mompPaymentResponse.getRespCode());
                    bizResponse.setRespDesc(mompPaymentResponse.getRespDesc());
                    return bizResponse;
                } else {
                    rglog.info("查证超时,拒绝交易.");
                    mompPaymentResponse.setAcctStatus(AcctStatusEnum.FAIL.getAcctStatus());
                    mompPaymentResponse.setFailureReason("打款超时,请重试.");
                    mompPaymentResponse.setRespCode(RespCodeEnum.SYSTEM_ERROR.getRespCode());
                    mompPaymentResponse.setRespDesc(RespCodeEnum.SYSTEM_ERROR.getRespDesc());
                    bizResponse.setRespCode(mompPaymentResponse.getRespCode());
                    bizResponse.setRespDesc(mompPaymentResponse.getRespDesc());
                    return bizResponse;
                }
            } else {
                // BompTMMcFundInfoFundStatusEnum.FAILURE.getStatus().equals(lastBompTMMcFundInfo.getFundStatus());
                //上次打款失败,正常打款
                rglog.info("上次打款失败,正常打款");
                return normalPayment(mompPaymentRequest, mompPaymentResponse, bizResponse);
            }
        }
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        MompPaymentResponse mompPaymentResponse = (MompPaymentResponse) bizResponse.getResult();
        ConvertUtil.convertInput(mompPaymentResponse);
    }

    //region 业务前检查

    private MompPaymentRequest beforeBizCheck(MompPaymentRequest mompPaymentRequest) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        /* 去除参数中的空格 */
        String jsonString = JsonUtil.toJson(mompPaymentRequest).replaceAll(" ", "");
        mompPaymentRequest = (MompPaymentRequest) JsonUtil.loadJson(MompPaymentRequest.class, jsonString);
        String instId = mompPaymentRequest.getHeader().getInstId();
        String chanlId = mompPaymentRequest.getHeader().getChanlId();
        String mchntNo = mompPaymentRequest.getMchntNo();

        /*渠道判断*/
        if (BompAppParamConstant.MCMP_CHANNEL.equals(chanlId) || "WECHAT".equals(chanlId) || "MOBILE".equals(chanlId) || "PCWEB".equals(chanlId)) {
            //允许交易
        } else {
            //渠道错误
            rglog.error("此交易不支持该渠道:<{}>.", chanlId);
            throw new BizException(RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespCode(), RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespDesc());
        }

        /* 对交易金额进行处理,转为两位小数 */
        String adjustAmt = mompPaymentRequest.getAdjustAmt();
        rglog.debug("订单金额：{}", adjustAmt);
        try {
            adjustAmt = AmountUtil.checkAmt(adjustAmt, 2, false, false);
            mompPaymentRequest.setAdjustAmt(adjustAmt);
        } catch (Exception e) {
            rglog.error("订单金额非法.");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), "订单金额非法");
        }

        /*BSPS调用,校验短信验证码和商户信息和付款账号是否本行卡*/
        if ("WECHAT".equals(chanlId) || "MOBILE".equals(chanlId) || "PCWEB".equals(chanlId)) {
            boolean smsCheckStatus = verifySmsCode(mompPaymentRequest);
            if (!smsCheckStatus) {
                rglog.error("短信验证码校验失败！");
                throw new BizException(OltpRpcdEnum.VERIFY_SMS_CODE_ERROR.getRespCode(), OltpRpcdEnum.VERIFY_SMS_CODE_ERROR.getRespDesc());
            }

            /*必填校验*/
            if (StringUtil.isEmptyOrNull(mompPaymentRequest.getPayerAcctNo())
                    || StringUtil.isEmptyOrNull(mompPaymentRequest.getCertType())
                    || StringUtil.isEmptyOrNull(mompPaymentRequest.getCertNo())
                    || StringUtil.isEmptyOrNull(mompPaymentRequest.getMobile())) {
                rglog.debug("必填校验失败.");
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            }

            /*获取商户信息*/
            MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
            MchntBaseInfo mchntBaseInfo = mchntBaseInfoMapper.selectMchntBaseInfoByPrimaryKey(instId, mchntNo);
            if (mchntBaseInfo == null) {
                rglog.error("获取商户信息失败！instId<{}>,mchntNo<{}>", instId, mchntNo);
                throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
            }
            xmlTreeUtil.setXmlTreeObjectValue("mchntBaseInfo", mchntBaseInfo);

            /*敏感字段解密*/
            String session = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SESSION);
            UserPermissionCheckService userService = new UserPermissionCheckServiceImpl();
            UserSessionInfo userSessionInfo = userService.checkSessionStatus(instId, session);
            String acctNo = mompPaymentRequest.getPayerAcctNo();
            acctNo = descriptData(userSessionInfo.getSensitiveKey(), acctNo);
            mompPaymentRequest.setPayerAcctNo(acctNo);

            String certNo = mompPaymentRequest.getCertNo();
            certNo = descriptData(userSessionInfo.getSensitiveKey(), certNo);
            mompPaymentRequest.setCertNo(certNo);

            String mobile = mompPaymentRequest.getMobile();
            mobile = descriptData(userSessionInfo.getSensitiveKey(), mobile);
            mompPaymentRequest.setMobile(mobile);

            rglog.debug("解密后请求报文:<{}>", JsonUtil.toJson(mompPaymentRequest));

            /*付款账号判断*/
            if (!isSelfBankCard(mompPaymentRequest)) {
                //非本行卡,不允许进行营销
                rglog.error("非本行卡,不允许进行营销！");
                throw new BizException(RespCodeEnum.NOT_BANK_CARD.getRespCode(), RespCodeEnum.NOT_BANK_CARD.getRespDesc());
            }
            rglog.debug("本行卡,可以进行营销.");
        }

        /*营销活动校验*/
        if ("WECHAT".equals(chanlId) || "MOBILE".equals(chanlId) || "PCWEB".equals(chanlId)) {
            BompMcInfoMapper mcMoInfoMapper = new BompMcInfoMapperImpl();
            BompMcInfo bompMcMoInfo = mcMoInfoMapper.selectBompMcInfoByPrimaryKey(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID), mompPaymentRequest.getMcNo());
            if (null == bompMcMoInfo) {
                rglog.error("没有此营销活动.");
                throw new BizException(RespCodeEnum.PARAM_ERROR.getRespCode(), "无此营销活动" + mompPaymentRequest.getMcNo());
            }
            /*活动状态校验*/
            if ("0".equals(bompMcMoInfo.getBudgetRechargeMethod())) {
                rglog.error("活动预算方式<{}>不需要进行打款", bompMcMoInfo.getBudgetRechargeMethod());
                throw new BizException(RespCodeEnum.PARAM_ERROR.getRespCode(), "活动预算方式不需要进行打款");
            }
//            String mcStatus = bompMcMoInfo.getMcStatus();
//            if (!"0".equals(mcStatus)) {
//                rglog.error("活动状态<{}>非0(草稿状态),不允许打款.", mcStatus);
//                throw new BizException(RespCodeEnum.PARAM_ERROR.getRespCode(), RespCodeEnum.PARAM_ERROR.getRespDesc());
//            }
            //需打款金额
            String needAdjustAmt = "";
            if ("0".equals(bompMcMoInfo.getSponsor())) {
                rglog.error("银行全资活动不允许商户打款.");
                throw new BizException(RespCodeEnum.PARAM_ERROR.getRespCode(), "银行全资活动不允许商户打款");
            } else if ("1".equals(bompMcMoInfo.getSponsor())) {
                //商户总打款金额=总预算-银行打款金额
                String mchntTotalAmt = AmountUtil.subtraction(bompMcMoInfo.getBudget(), bompMcMoInfo.getBankBudget());
                //单商户打款金额=商户总打款金额/预期参与商户数量
                needAdjustAmt = AmountUtil.division(mchntTotalAmt, bompMcMoInfo.getExpectMchntQty());
            } else {
                //"2".equals(bompMcMoInfo.getSponsor());
                //商户全资,预算=打款金额
                needAdjustAmt = bompMcMoInfo.getBudget();
            }
            //须打款金额转两位小数
            needAdjustAmt = new BigDecimal(needAdjustAmt).setScale(2).toString();
            if (!needAdjustAmt.equals(adjustAmt)) {
                rglog.error("须打款金额<{}>与欲打款金额<{}>不符,拒绝打款.", needAdjustAmt, adjustAmt);
                throw new BizException(RespCodeEnum.PARAM_ERROR.getRespCode(), "打款金额不符");
            }

        } else {
            //"BOMP".equals(chanlId);
//            BompMcInfoMapper mcMoInfoMapper = new BompMcInfoMapperImpl();
//            BompMcInfo bompMcMoInfo = mcMoInfoMapper.selectBompMcInfoByPrimaryKey(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID), mompPaymentRequest.getMcNo());
//            if (null == bompMcMoInfo) {
//                rglog.error("没有此营销活动.");
//                throw new BizException(RespCodeEnum.PARAM_ERROR.getRespCode(), RespCodeEnum.PARAM_ERROR.getRespDesc());
//            }
//            /*活动状态校验*/
//            if ("0".equals(bompMcMoInfo.getBudgetRechargeMethod())) {
//                rglog.error("活动预算方式<{}>不需要进行打款", bompMcMoInfo.getBudgetRechargeMethod());
//                throw new BizException(RespCodeEnum.PARAM_ERROR.getRespCode(), RespCodeEnum.PARAM_ERROR.getRespDesc());
//            }
//            //需打款金额
//            String needAdjustAmt = "";
//            if ("0".equals(bompMcMoInfo.getSponsor())) {
//                //银行全资,预算=打款金额
//                needAdjustAmt = bompMcMoInfo.getBudget();
//            } else if ("1".equals(bompMcMoInfo.getSponsor())) {
//                //银商联合
//                needAdjustAmt = bompMcMoInfo.getBankBudget();
//            } else {
//                //"2".equals(bompMcMoInfo.getSponsor());
//                rglog.error("商户全资活动不允许银行打款.");
//                throw new BizException(RespCodeEnum.PARAM_ERROR.getRespCode(), RespCodeEnum.PARAM_ERROR.getRespDesc());
//            }
//            //须打款金额转两位小数
//            needAdjustAmt = new BigDecimal(needAdjustAmt).setScale(2).toString();
//            if (!needAdjustAmt.equals(adjustAmt)) {
//                rglog.error("须打款金额<{}>与欲打款金额<{}>不符,拒绝打款.", needAdjustAmt, adjustAmt);
//                throw new BizException(RespCodeEnum.PARAM_ERROR.getRespCode(), RespCodeEnum.PARAM_ERROR.getRespDesc());
//            }
        }
        return mompPaymentRequest;
    }

    /**
     * 判断是不是本行卡
     */
    private boolean isSelfBankCard(MompPaymentRequest mompPaymentRequest) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String instId = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID);
        String acctNo = mompPaymentRequest.getPayerAcctNo();

        BinInfoService binInfoService = new BinInfoServiceImpl();
        BinInfo binInfo = binInfoService.getCardBinInfo(acctNo);
        if (null == binInfo) {
            rglog.error("通过结算卡号查询卡bin信息为空！acctNo:<{}>", acctNo);
            throw new BizException(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode(), RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
        }
        rglog.debug("卡Bin信息:<{}>", JSONObject.toJSONString(binInfo));

        //查询该法人行的银联机构号
        SysParamMapper sysParamMapper = new SysParamMapperImpl();
        SysParam sysParam = sysParamMapper.selectSysParamByPrimaryKey(instId, "OPMS_SYS_PARAM", "CORPORATION_ORG_CODE");
        if (null == sysParam) {
            rglog.error("获取<{}>的银联机构号失败<{}>", instId, "OPMS_SYS_PARAM,CORPORATION_ORG_CODE");
            throw new BizException(RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespCode(), RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespDesc());
        }
        if (binInfo.getIssuerCode().substring(0, 4).equals(sysParam.getParamValue().substring(0, 4))) {
            /* 本行卡 */
            return true;
        } else {
            /* 他行卡 */
            return false;
        }
    }

    /**
     * 解密
     *
     * @param sensitiveKey 敏感信息加密密钥
     * @param encData      密文
     * @return 解密后明文
     * @throws Exception 异常信息
     */
    private String descriptData(String sensitiveKey, String encData) throws Exception {
        //目前只支持AES PKCS7-CBC
        String algorithmType = "AES";
        if ("AES".equals(algorithmType)) {
            String descData = AESUtil.pkcs7CbcDecryptData(Base64.decodeBase64(sensitiveKey), Base64.decodeBase64(encData));
            return descData;
        } else {
            byte[] bEncData = Base64.decodeBase64(encData);
            byte[] descData = new byte[bEncData.length];
            int retCode = SM4Util.sms4(bEncData, bEncData.length, ByteUtil.hexStringToByte(sensitiveKey), descData, 0);
            if (retCode == 0) {
                for (int i = 0; i < descData.length; i++) {
                    if (descData[i] == 0) {
                        return new String(descData, 0, i);
                    }
                }
                return new String(descData);
            }
        }

        return null;
    }

    /**
     * 验证短信验证码
     */
    private boolean verifySmsCode(MompPaymentRequest mompPaymentRequest) throws Exception {
        String smsCode = mompPaymentRequest.getAuthCode();
        String smsAuthId = mompPaymentRequest.getTransSeqNum();
        SmsService smsService = new SmsServiceImpl();
        boolean smsCheckStatus = smsService.verifySmsCode(mompPaymentRequest.getHeader().getInstId(), SmsTypeEnum.ACCT_RECHARGE.getSmsType(), smsCode, smsAuthId);
        return smsCheckStatus;
    }

    //endregion

    //region 正常打款

    private BizResponse normalPayment(MompPaymentRequest mompPaymentRequest, MompPaymentResponse mompPaymentResponse, BizResponse bizResponse) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        //正常打款
        /*step1.获取收款账号*/
        String payeeActualAcct = getPayeeActualAcct(mompPaymentRequest);
        if (payeeActualAcct == null) {
            throw new BizException(RespCodeEnum.NO_MC_ACCOUNT_INFO_ERROR.getRespCode(), RespCodeEnum.NO_MC_ACCOUNT_INFO_ERROR.getRespDesc());
        }
        rglog.debug("获取营销打款收款账号:<{}>", payeeActualAcct);

        /*step2.登记三张订单表*/
        if (!insertThreeOrderInfo(mompPaymentRequest)) {
            //登记失败
            String failureReason = "【营销打款】登记订单表失败！";
            rglog.error(failureReason);
            mompPaymentResponse.setRespCode(RespCodeEnum.SYSTEM_ERROR.getRespCode());
            mompPaymentResponse.setRespDesc(failureReason);
            mompPaymentResponse.setFailureReason(failureReason);
            mompPaymentResponse.setAcctStatus(AcctStatusEnum.FAIL.getAcctStatus());
            bizResponse.setRespCode(mompPaymentResponse.getRespCode());
            bizResponse.setRespDesc(mompPaymentResponse.getRespDesc());
            return bizResponse;
        }
        rglog.debug("【营销打款】登记订单表成功.");

        /*step3.TODO 调用ESB营销核心记账,根据记账结果更新订单表,登记打款记录表*/

        mompPaymentResponse.setAcctStatus(AcctStatusEnum.SUCCESS.getAcctStatus());
        mompPaymentResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        mompPaymentResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setRespCode(mompPaymentResponse.getRespCode());
        bizResponse.setRespDesc(mompPaymentResponse.getRespDesc());
        return bizResponse;
    }

    /**
     * 取数据库收款账户信息数据
     * 根据请求中的法人机构号、科目/账号标识、角色标识(法人机构号+777777)
     */
    private String getPayeeActualAcct(MompPaymentRequest mompPaymentRequest) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String globalInstId = mompPaymentRequest.getHeader().getInstId();//法人机构号
        String headOfficeId = globalInstId + "777777";//角色标识
        BompTCRoleAcctInfoMapper tcRoleAcctInfoMapper = new BompTCRoleAcctInfoMapperImpl();
        BompTCRoleAcctInfo tcRoleAcctInfo = null;
        try {
            tcRoleAcctInfo = tcRoleAcctInfoMapper.selectInstitutionMcAccountByOrgIdAndAccountCategory(globalInstId, BompAppParamConstant.MOMP_SUBJECT, headOfficeId);
        } catch (Exception e) {
            rglog.error(e.getMessage());
        }
        if (null == tcRoleAcctInfo) {
            rglog.error("获取法人机构<{}>的总行机构<{}>的营销收款账户信息失败!", globalInstId, headOfficeId);
            return null;
        }
        String payeeActualAcct = tcRoleAcctInfo.getActualAcct();//收款账户
        xmlTreeUtil.setXmlTreeStringValue(BompTreeNodeConstant.PAYEE_ACTUAL_ACCT, payeeActualAcct);
        return payeeActualAcct;
    }
    //endregion

    //region 操作订单表

    /**
     * 登记三张订单表
     */
    private boolean insertThreeOrderInfo(MompPaymentRequest mompPaymentRequest) throws Exception {
        UserOrderInfo userOrderInfo = initUserOrderInfo(mompPaymentRequest);
        MchntOrderInfo mchntOrderInfo = initMchntOrderInfo(mompPaymentRequest);
        PayOrderInfo payOrderInfo = initPayOrderInfo(mompPaymentRequest);
        //登记订单表（用户订单，商户订单，支付订单）
        OrderService orderService = new OrderServiceImpl();
        return orderService.registerOrderInfo(userOrderInfo, Arrays.asList(mchntOrderInfo), payOrderInfo);
    }

    /**
     * 初始化用户订单
     */
    private UserOrderInfo initUserOrderInfo(MompPaymentRequest mompPaymentRequest) throws Exception {
        UserOrderInfo userOrderInfo = new UserOrderInfo();
        Header header = mompPaymentRequest.getHeader();
        ConvertUtil.convertOutput(userOrderInfo);
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        userOrderInfo.setUserId(mompPaymentRequest.getUserId());
        userOrderInfo.setOrderAmt(mompPaymentRequest.getAdjustAmt());
        userOrderInfo.setRealPayAmt(mompPaymentRequest.getAdjustAmt());
        userOrderInfo.setFrontSeqNum(header.getTraceNo());
        userOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        userOrderInfo.setBizStatus(BizStatusEnum.INIT.getStatus());
        //region 必填
        userOrderInfo.setInstId(header.getInstId());
        userOrderInfo.setTxnDate(header.getTransDate());
        userOrderInfo.setTxnTime(header.getTransTime());
        userOrderInfo.setTxnNum(header.getTxnNum());
        userOrderInfo.setBizType(header.getBizType());
        userOrderInfo.setMsgSrcId(header.getSrcSysId());
        userOrderInfo.setTransChannelId(header.getChanlId());
        userOrderInfo.setMchntOrderId(sysSeqNum);
        userOrderInfo.setSysSeqNum(sysSeqNum);

        Date date = new Date();
        String currentDateTime = DateUtil.getDateByTimeStamp(date.getTime(), BompAppParamConstant.yyyyMMddHHmmss);
        userOrderInfo.setOrderCreateTime(currentDateTime);
        long expiryTime = date.getTime() + 5 * 60 * 1000L;
        String orderExpiryTime = DateUtil.getDateByTimeStamp(expiryTime, BompAppParamConstant.yyyyMMddHHmmss);
        userOrderInfo.setOrderExpiryTime(orderExpiryTime);
        //订单状态,在调用ESB后进行修改
        userOrderInfo.setOrderStatus(OrderStatusEnum.INIT.getStatus());
        //创建时间
        currentDateTime = DateUtil.getDateByTimeStamp(date.getTime(), BompAppParamConstant.yyyy_MM_dd_HHmmssSSS);
        userOrderInfo.setCreateTime(currentDateTime);
        //endregion
        return userOrderInfo;
    }

    /**
     * 初始化商户订单
     */
    private MchntOrderInfo initMchntOrderInfo(MompPaymentRequest mompPaymentRequest) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        MchntOrderInfo mchntOrderInfo = new MchntOrderInfo();
        // ConvertUtil.convertOutput(mchntOrderInfo);
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        Header requestHeader = mompPaymentRequest.getHeader();
        String chanlId = requestHeader.getChanlId();
        if (BompAppParamConstant.MCMP_CHANNEL.equals(chanlId)) {
            //如果是MCMP调用,收单机构号填"机构号+777777",商户名填默认商户名
            mchntOrderInfo.setAcqInstCode(requestHeader.getInstId() + "777777");
            mchntOrderInfo.setIndustryType(" ");
            mchntOrderInfo.setMchntName(BompAppParamConstant.PAYER_NAME);
        } else if ("WECHAT".equals(chanlId) || "MOBILE".equals(chanlId) || "PCWEB".equals(chanlId)) {
            //如果是BSPS调用,填商户基础信息
            MchntBaseInfo mchntBaseInfo = (MchntBaseInfo) xmlTreeUtil.getXmlTreeObjectValue("mchntBaseInfo", MchntBaseInfo.class);
            mchntOrderInfo.setAcqInstCode(mchntBaseInfo.getSignInstId());
            mchntOrderInfo.setIndustryType(mchntBaseInfo.getIndustryType());
            mchntOrderInfo.setMchntName(mchntBaseInfo.getMchntName());
        }

        mchntOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        mchntOrderInfo.setBizProdCode(mompPaymentRequest.getHeader().getBizType());
        // mchntOrderInfo.setMchntDiscountFee("0.00");

        //region 必填
        mchntOrderInfo.setInstId(requestHeader.getInstId());
        mchntOrderInfo.setTxnDate(requestHeader.getTransDate());
        mchntOrderInfo.setTxnTime(requestHeader.getTransTime());
        mchntOrderInfo.setTxnNum(requestHeader.getTxnNum());
        mchntOrderInfo.setBizType(requestHeader.getBizType());
        mchntOrderInfo.setBizProdCode(BaseProdEnum.BASIC.getProdCode());
        mchntOrderInfo.setSysSeqNum(sysSeqNum);
        mchntOrderInfo.setMchntOrderId(sysSeqNum);
        mchntOrderInfo.setMchntNo(mompPaymentRequest.getMchntNo());
        mchntOrderInfo.setOrderCcy("156");
        mchntOrderInfo.setOrderAmt(mompPaymentRequest.getAdjustAmt());
        mchntOrderInfo.setRealSettleAmt(mompPaymentRequest.getAdjustAmt());
        mchntOrderInfo.setCreateTime(DateUtil.getCurrentDateTime(BompAppParamConstant.yyyy_MM_dd_HHmmssSSS));
        mchntOrderInfo.setRealSettleFlag("N");
        //endregion
        xmlTreeUtil.setXmlTreeObjectValue("mchntOrderInfo", mchntOrderInfo);
        return mchntOrderInfo;
    }

    /**
     * 初始化支付订单
     */
    private PayOrderInfo initPayOrderInfo(MompPaymentRequest mompPaymentRequest) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        MchntOrderInfo mchntOrderInfo = (MchntOrderInfo) xmlTreeUtil.getXmlTreeObjectValue("mchntOrderInfo", MchntOrderInfo.class);
        Header requestHeader = mompPaymentRequest.getHeader();
        PayOrderInfo payOrderInfo = new PayOrderInfo();
        // ConvertUtil.convertOutput(payOrderInfo);
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        //region 必填
        payOrderInfo.setInstId(requestHeader.getInstId());
        payOrderInfo.setTxnDate(requestHeader.getTransDate());
        payOrderInfo.setTxnTime(requestHeader.getTransTime());
        payOrderInfo.setTxnNum(requestHeader.getTxnNum());
        payOrderInfo.setBizType(requestHeader.getBizType());
        payOrderInfo.setSysSeqNum(sysSeqNum);
        payOrderInfo.setMchntOrderId(mchntOrderInfo.getMchntOrderId());
        payOrderInfo.setOrderCcy(mchntOrderInfo.getOrderCcy());
        payOrderInfo.setOrderAmt(mchntOrderInfo.getOrderAmt());
        payOrderInfo.setMsgDstId(ChannelEnum.ESB.getChannelType());
        payOrderInfo.setUserId(mompPaymentRequest.getUserId());
        payOrderInfo.setTxnNum(requestHeader.getTxnNum());
        payOrderInfo.setChannelSeqNum(sysSeqNum);
        payOrderInfo.setDstCallIndex("0");
        payOrderInfo.setDstTxnNum("00010000175500");
        String esbSysSeqNum = xmlTreeUtil.getXmlTreeStringValue(BompTreeNodeConstant.ESB_SYS_SEQ_NUM);
        payOrderInfo.setChannelReconKey(esbSysSeqNum);//ESB流水号
        payOrderInfo.setCreateTime(DateUtil.getCurrentDateTime(BompAppParamConstant.yyyy_MM_dd_HHmmssSSS));
        //endregion

        payOrderInfo.setMchntNo(mchntOrderInfo.getMchntNo());
        payOrderInfo.setRealPayAmt(mompPaymentRequest.getAdjustAmt());
        payOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        payOrderInfo.setPayerAcctInfo(mompPaymentRequest.getPayerAcctNo());

        /*一定是本行卡,业务开始前已经校验,不允许使用他行卡进行营销*/
        payOrderInfo.setPayerAcctType(AcctTypeEnum.BANK_ACCT.getAcctType());

        String payeeActualAcct = xmlTreeUtil.getXmlTreeStringValue(BompTreeNodeConstant.PAYEE_ACTUAL_ACCT);
        payOrderInfo.setPayeeAcctInfo(payeeActualAcct);
        payOrderInfo.setPayeeAcctType(AcctTypeEnum.BANK_ACCT.getAcctType());
        payOrderInfo.setPayType(PayTypeEnum.BANK_CARD.getPayType());
        payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());

        return payOrderInfo;
    }

    /**
     * 更改订单状态
     *
     * @param mompPaymentRequest 接口请求对象
     * @param sysSeqNum          交易流水号,用于查询原订单(正常打款时传系统流水号,查证后修改时传打款记录表中的打款流水号)
     * @param transStatus        交易状态:0-初始状态     * 1-交易成功     * 2-交易失败     * 3-交易超时"
     * @return 更改结果, true-成功|false-失败
     * @throws Exception 异常信息
     */
    private boolean isUpdateOrderStatus(MompPaymentRequest mompPaymentRequest, String sysSeqNum, String transStatus) throws Exception {
        rglog.info("开始更改订单状态,交易结果:<{}>", transStatus);
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        // String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        String instId = mompPaymentRequest.getHeader().getInstId();
        String updateTime = DateUtil.getCurrentDateTime(BompAppParamConstant.yyyy_MM_dd_HHmmssSSS);

        //region 查询、更新 用户订单、商户订单、支付订单
        /*用户订单*/
        UserOrderInfoMapper userOrderInfoMapper = new UserOrderInfoMapperImpl();
        UserOrderInfo userOrderInfo = userOrderInfoMapper.selectUserOrderInfoByPrimaryKey(instId, sysSeqNum);
        if (userOrderInfo == null) {
            throw new BizException(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode(), RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
        }
        rglog.debug("查询用户订单:<{}>", JsonUtil.toJson(userOrderInfo));
        if (TransStatusEnum.TRANS_SUCC.getStatus().equals(transStatus)) {
            //成功
            userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
            userOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
        } else if (TransStatusEnum.TRANS_TIMEOUT.getStatus().equals(transStatus)) {
            //超时/未知
            userOrderInfo.setOrderStatus(OrderStatusEnum.INIT.getStatus());
            userOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
        } else {
            //失败
            userOrderInfo.setOrderStatus(OrderStatusEnum.CLOSE.getStatus());
            userOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
        }
        userOrderInfo.setTransStatus(transStatus);
        userOrderInfo.setUpdateTime(updateTime);

        /*商户订单*/
        MchntOrderInfoMapper mchntOrderInfoMapper = new MchntOrderInfoMapperImpl();
        MchntOrderInfo mchntOrderInfo = mchntOrderInfoMapper.selectMchntOrderInfoByPrimaryKey(instId, sysSeqNum, mompPaymentRequest.getMchntNo());
        if (mchntOrderInfo == null) {
            throw new BizException(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode(), RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
        }
        rglog.debug("查询商户订单:<{}>", JsonUtil.toJson(mchntOrderInfo));
        mchntOrderInfo.setTransStatus(transStatus);
        mchntOrderInfo.setUpdateTime(updateTime);

        /*支付订单*/
        PayOrderInfoMapper payOrderInfoMapper = new PayOrderInfoMapperImpl();
        List<PayOrderInfo> payOrderInfoList = payOrderInfoMapper.selectPayOrderInfoBySysSeqNum(instId, sysSeqNum);
        if (payOrderInfoList == null || payOrderInfoList.size() != 1) {
            throw new BizException(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode(), RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
        }
        PayOrderInfo payOrderInfo = payOrderInfoList.get(0);
        rglog.debug("查询支付订单:<{}>", JsonUtil.toJson(payOrderInfo));
        payOrderInfo.setTransStatus(transStatus);
        payOrderInfo.setUpdateTime(updateTime);
        if (TransStatusEnum.TRANS_SUCC.getStatus().equals(transStatus)) {
            //调用成功记录ESB支付通道流水号
            String channelSeqNum = xmlTreeUtil.getXmlTreeStringValue(BompTreeNodeConstant.ESB_CHANNEL_SEQ_NUL);
            payOrderInfo.setChannelSeqNum(channelSeqNum);
            payOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
            payOrderInfo.setSettleDate(xmlTreeUtil.getXmlTreeStringValue("settleDate"));
        } else if (TransStatusEnum.TRANS_TIMEOUT.getStatus().equals(transStatus)) {
            //超时/未知
            payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
        } else {
            //失败
            payOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
        }
        //endregion

        OrderService orderService = new OrderServiceImpl();
        return orderService.updateOrderInfo(userOrderInfo, Arrays.asList(mchntOrderInfo), payOrderInfo);
    }

    /**
     * 更改原交易订单状态
     *
     * @param mompPaymentRequest 接口请求对象
     * @param transStatus        交易状态:0-初始状态     * 1-交易成功     * 2-交易失败     * 3-交易超时"
     * @return 更改结果, true-成功|false-失败
     */
    private boolean isUpdateOrigOrderStauts(MompPaymentRequest mompPaymentRequest, String transStatus) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        BompTMMcFundInfo bompTMMcFundInfo = (BompTMMcFundInfo) xmlTreeUtil.getXmlTreeObjectValue("bompTMMcFundInfo", BompTMMcFundInfo.class);
        String OrigOrderSysSeqNum = bompTMMcFundInfo.getRecordIndex();

        return isUpdateOrderStatus(mompPaymentRequest, OrigOrderSysSeqNum, transStatus);

    }
    //endregion


    /**
     * 异步查证
     */
    private boolean isAsynCoreGeneralTransQuery(MompPaymentRequest mompPaymentRequest) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String instId = mompPaymentRequest.getHeader().getInstId();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        String transDate = mompPaymentRequest.getHeader().getTransDate();
        //region 初始化请求对象
        //TODO 异步调用交易查证
        return true;
    }

    /**
     * 同步查证,是否交易成功,0-超时|1-成功|2-失败
     */
    private int queryOrderDone(MompPaymentRequest mompPaymentRequest) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        //TODO 同步调用查证接口,是否交易成功,0-超时|1-成功|2-失败
        return 1;
    }

    /**
     * 初始化营销活动打款记录
     */
    private BompTMMcFundInfo initTmMcFundInfo(MompPaymentRequest mompPaymentRequest, String fundStatus) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String payeeActualAcct = xmlTreeUtil.getXmlTreeStringValue(BompTreeNodeConstant.PAYEE_ACTUAL_ACCT);
        Header header = mompPaymentRequest.getHeader();
        String chanlId = header.getChanlId();
        //region 必填
        BompTMMcFundInfo tmMcFundInfo = new BompTMMcFundInfo();
        /*区分渠道*/
        if (BompAppParamConstant.MCMP_CHANNEL.equals(chanlId)) {
            tmMcFundInfo.setPayerAcctId(mompPaymentRequest.getHeader().getInstId());
            tmMcFundInfo.setPayerAcctType(PayerAcctTypeEnum.BANK.getCode());
            tmMcFundInfo.setPayerAcctName(BompAppParamConstant.PAYER_NAME);
        } else if ("WECHAT".equals(chanlId) || "MOBILE".equals(chanlId) || "PCWEB".equals(chanlId)) {
            //BSPS调用
            tmMcFundInfo.setPayerAcctId(mompPaymentRequest.getMchntNo());
            tmMcFundInfo.setPayerAcctType(PayerAcctTypeEnum.MCHNT.getCode());
            tmMcFundInfo.setPayerAcctName(mompPaymentRequest.getPayerAcctName());
        }

        tmMcFundInfo.setInstId(header.getInstId());
        tmMcFundInfo.setMcNo(mompPaymentRequest.getMcNo());

        //存系统流水号
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        tmMcFundInfo.setRecordIndex(sysSeqNum);
        tmMcFundInfo.setPayerAcctNo(mompPaymentRequest.getPayerAcctNo());
        tmMcFundInfo.setPayeeAcctNo(payeeActualAcct);
        tmMcFundInfo.setFundAmt(mompPaymentRequest.getAdjustAmt());
        tmMcFundInfo.setFundStatus(fundStatus);
        tmMcFundInfo.setOprId(mompPaymentRequest.getUserId());
        tmMcFundInfo.setCreateTime(DateUtil.getCurrentDateTime(BompAppParamConstant.yyyy_MM_dd_HHmmssSSS));
        //endregion
        return tmMcFundInfo;
    }

    /**
     * 插入营销活动打款记录表
     */
    private boolean isInsertOrUpdateTMMcFundInfo(BompTMMcFundInfo tmMcFundInfo) throws Exception {
        BompTMMcFundInfoMapper tmMcFundInfoMapper = new BompTMMcFundInfoMapperImpl();
        int nResult = tmMcFundInfoMapper.insertSingleRecordForMchntFundInfo(tmMcFundInfo);
        if (nResult == Database.DBS_SUCCESS) {
            return true;
        }
        return false;
    }

    /**
     * 更新营销打款记录表
     */
    private boolean isUpdateTMMcFundInfo(BompTMMcFundInfo tmMcFundInfo, String userId, String status) throws Exception {
        String updateTime = DateUtil.getCurrentDateTime(BompAppParamConstant.yyyy_MM_dd_HHmmssSSS);
        tmMcFundInfo.setUpdateTime(updateTime);
        tmMcFundInfo.setFundStatus(status);
        tmMcFundInfo.setLastOprId(userId);
        BompTMMcFundInfoMapper bompTMMcFundInfoMapper = new BompTMMcFundInfoMapperImpl();
        int nResult = bompTMMcFundInfoMapper.updateTMMcFundInfo(tmMcFundInfo);
        if (nResult == Database.DBS_SUCCESS) {
            return true;
        }
        return false;
    }
    //endregion

    //region 商户服务打款成功,调用营销发布进入测试

    /**
     * 更改营销活动状态为测试中
     */
    private void mchntMcPublish(String mcNo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String instId = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID);
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        String mchntNo = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.MCHNT_NO);
        DubboService dubboService = new DubboServiceImpl();
        MchntMcPublishRequest mchntMcPublishRequest = new MchntMcPublishRequest();
        cc.rengu.igas.momp.facade.base.Header mompHeader = new cc.rengu.igas.momp.facade.base.Header();
        ConvertUtil.convertOutput(mompHeader);
        mompHeader.setSrcSysId(AppParamConstant.SYS_ID);
        mompHeader.setChanlId(ChannelEnum.BSPS.getChannelType());
        mompHeader.setTxnNum("M00MO027");
        mompHeader.setTraceNo(sysSeqNum + "1");

        MchntBaseInfo mchntBaseInfo = (MchntBaseInfo) xmlTreeUtil.getXmlTreeObjectValue("mchntBaseInfo", MchntBaseInfo.class);
        mchntMcPublishRequest.setHeader(mompHeader);
        mchntMcPublishRequest.setQueryType("1");
        mchntMcPublishRequest.setQueryId(mchntNo);
        mchntMcPublishRequest.setQueryOrgId(mchntBaseInfo.getSignInstId());
        mchntMcPublishRequest.setQueryRole("10");
        mchntMcPublishRequest.setMcNo(mcNo);
        mchntMcPublishRequest.setOprType("4");//4-打款完成进入测试

        int iReturnCode = dubboService.asynCallDubboService("manageMchntMcService", "publishMchntMc", mchntMcPublishRequest, "DubboAsynBaseService");
        if (iReturnCode != 0) {
            rglog.error("调用营销发布失败.");
        }
    }
    //endregion
}
